import logging.handlers
from common.path_setting import ensure_path_sep
import time
import colorlog


class GetLogger:
    logger = None
    log_colors_config = {
        'DEBUG': 'cyan',
        'INFO': 'green',
        'WARNING': "yellow",
        'ERROR': 'red',
        'CRITICAL': 'red',
    }

    # 获取logger
    @classmethod
    def get_logger(cls):
        # 日志器
        if cls.logger is None:
            cls.logger = logging.getLogger("xzk")
            cls.logger.setLevel(logging.INFO)

            # 格式器
            fmh = '%(log_color)s %(levelname)s  %(asctime)s  [%(name)s]  [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s'
            fmt = '%(levelname)s  %(asctime)s  [%(name)s]  [%(filename)s(%(funcName)s:%(lineno)d)] - %(message)s'

            fh = colorlog.ColoredFormatter(fmh, log_colors=cls.log_colors_config)
            ft = logging.Formatter(fmt)

            # 处理器
            # 控制台输出
            sh = logging.StreamHandler()
            now_time = time.strftime('%Y%m%d%H%M%S', time.localtime())
            log_path = ensure_path_sep(f"//outputs//logs//{now_time}.log")
            # 日志文件输出
            st = logging.handlers.TimedRotatingFileHandler(filename=log_path,
                                                           when="midnight",
                                                           interval=1,
                                                           backupCount=30,
                                                           encoding="utf-8")

            # 处理器格式化
            sh.setFormatter(fh)
            st.setFormatter(ft)

            cls.logger.addHandler(sh)
            cls.logger.addHandler(st)

        return cls.logger